<template>
	<view>
		<view class="hbg">
			
			<!-- 安全距离 - 刘海屏以及小程序胶囊位置距离 -->
			<view :style="{height: menuBarHeight + 'px'}"></view>
			
			<!-- 用户信息 -->
			<view class="user-info" @click="toLogin" v-if="memberinfo">
				<image class="avatar" :src="memberinfo.avatar || require('@/static/public/logo.png')" mode="aspectFill"></image>
				<view class="flex" style="flex-direction: column;">
					<text class="nickname" style="align-self: flex-start;">{{ memberinfo.nickname || '去登陆' }}</text>
					<text class="phone" style="align-self: flex-start;">{{ memberinfo.mobile || '' }}</text>
				</view>
			</view>
			
			<view class="user-info" @click="toLogin" v-else>
				<image class="avatar" src="@/static/public/logo.png" mode="aspectFill"></image>
				<view class="flex" style="flex-direction: column;">
					<text class="nickname" style="align-self: flex-start;">{{ '去登陆' }}</text>
					<text class="phone" style="align-self: flex-start;">{{ '' }}</text>
				</view>
			</view>
			
			<!-- 会员卡片 -->
			<view class="vip-card">
				<view class="light-border"></view>
				<view class="vip-title" style="justify-content: space-between;">
					<view class="flex" style="justify-content: space-between;width: 100%;padding: 10rpx 0" v-if="isVip">
						<view class="flex">
							<image class="vip-icon" src="@/static/mine/vip-icon.png" mode="aspectFill"></image>
							<text class="vip-text" style="margin-left: 10rpx;">尊贵会员</text>
						</view>
						<view class="flex" @tap="toVipPage()">
							<text class="vip-more">会员权益，充值有礼</text>
							<u-icon name="arrow-right" color="#F0D79F" size="26rpx"></u-icon>
						</view>
					</view>
					<block v-else>
						<view class="flex" style="flex-direction: column;">
							<text class="title">SVIP</text>
							<text class="desc">开通会员充值有礼，享更多权益</text>
						</view>
						<view class="button flex" style="justify-content: center;" @tap="toVipPage()">
							<text class="text">立即开通</text>
						</view>
					</block>
				</view>
				<view class="triangle-bottom"></view>
			</view>
		
			<!-- 钱包信息 -->
			<view class="wallet-info" @tap="goToWallet()">
				<view class="wallet-title">我的钱包</view>
				<view class="wallet-amounts">
					<view class="amount-item" :style="{ width: isFleetUser ? '50%' : '33.333%' }">
						<view><text class="amount">{{ (wallet.balance / 100).toFixed(2) || 0.00 }}</text></view>
						<text class="label">总金额</text>
					</view>
					<view class="amount-item" :style="{ width: isFleetUser ? '50%' : '33.333%' }" v-if="!isFleetUser">
						<view><text class="amount">{{ (wallet.balance / 100).toFixed(2) || 0.00 }}</text></view>
						<text class="label">可退金额</text>
					</view>
					<view class="amount-item" :style="{ width: isFleetUser ? '50%' : '33.333%' }" v-if="!isFleetUser">
					    <view><text class="amount">{{ (wallet.fleetBalance / 100).toFixed(2) || 0.00 }}</text></view>
					    <text class="label">车队余额</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 车辆信息 -->
		<view class="car">
			<view class="car-header">
				<text class="title">我的爱车</text>
				<view class="flex" @tap="toCarList()">
					<text class="view-all">全部车辆</text>
					<u-icon name="arrow-right" color="#fff" size="26rpx"></u-icon>
				</view>
			</view>
			<view class="car-info" style="margin-bottom: 0;">
				<view v-if="vehicleItem">
					<view class="title">
						<text class="text">车牌号码</text>
					</view>
					<view class="plate-number">
						<text class="plate-item" v-for="number in vehicleItem.plateNumber">{{ number }}</text>
					</view>
				</view>
				
				<view class="no-car flex" v-else @click="toCarList">
					<u-icon name="plus" size="60rpx" color="#C0C8D5" bold></u-icon>
					<text class="text">添加车辆</text>
				</view>
			</view>
			
			<!-- 充电按钮 -->
			<button v-if="memberinfo!= null && memberinfo.ifTestUser" class="charge-btn" @click="topSelfHelp">电站自助上线</button>
		</view>
		
		<view class="content">
			<view class="menu-list">
				<view class="menu-item" v-for="(item, index) in menuList" :key="index" @click="handleMenuClick(index)">
					<view class="menu-left">
						<view class="menu-icon">
							<image :src="getIconPath(item.icon)" mode="aspectFit" class="icon-image"></image>
						</view>
						<text class="menu-title">{{item.title}}</text>
					</view>
					<view class="menu-right">
					    <block v-if="item.value">
					        <text v-if="item.type === 'phone'" class="phone-number">{{item.value}}</text>
					        <u-badge v-if="item.type === 'badge'" max="99" :value="item.value"></u-badge>
					        <text v-if="item.type === 'fleet'" class="fleet-name">{{item.value}}</text>
							<text v-if="item.type === 'idCard'" class="idCard-name">{{item.value}}</text>
					    </block>
					    <u-icon v-if="item.showArrow !== false" name="arrow-right" color="#333" size="26rpx" bold></u-icon>
					    <image v-else-if="item.type === 'phone'" class="service-phone" src="@/static/mine/service-phone.png" mode="aspectFill"></image>
					</view>
				</view>
			</view>
		</view>
		
		<!-- <com-login ref="login" @myevent="uinfo"></com-login> -->
		<com-tabbar :currentTab="currentTab"></com-tabbar>
	</view>
</template>

<script>
	import { mapState, mapActions } from 'vuex';
	import { getNavBarHeight } from '@/utils/system.js';
	import { getIsFleetUser } from '@/common/cacheManager.js';
	export default {
		data() {
			return {
				currentTab: 'user',
				username: '立即登陆',
				showlogin1: true,
				showlogin2: false,
				money: '0.00',
				memberinfo: null,
				menuBarHeight: 0,
				isVip: false,
				cellIconStyle: {color: '#333', fontSize: '26rpx'},
				menuList: [
					{ title: '优惠券', icon: 'coupon', type: 'normal' },
					{ title: '我的充电桩', icon: 'charging', type: 'normal' },
					{ title: 'ID卡', icon: 'idCard', type: 'idCard',  showArrow: false, value: '' },
					{ title: '所属车队', icon: 'fleet', type: 'fleet',  showArrow: false, value: '' },
					{ title: '发票开具', icon: 'invoice', type: 'normal' },
					// { title: '切换语言', icon: 'language', type: 'normal' },
					{ title: '常见问题', icon: 'question', type: 'normal' },
					{ title: '服务热线', icon: 'service', type: 'phone', value: '' },
					{ title: '消息通知', icon: 'notification', type: 'badge', value: '' },
					{ title: '设置', icon: 'setting', type: 'normal' },
				],
				vehicleItem: null,
				wallet: {
					balance: 0,
					freezePrice: 0,
					freezePriceChedui: 0,
					fleetBalance: 0,
					idCardBalance: 0,
				},
				serviceHotLine: '', // 服务热线
				isFleetUser: false,
			}
		},
		computed: {
			...mapState(['loginState'])
		},
		onShow() {
			const { statusBarHeight, navBarHeight } = getNavBarHeight();
			this.menuBarHeight = navBarHeight;
			if (this.loginState) {
				this.getmemberinfo();
				// 在用户已登录的情况下获取 isFleetUser 状态
				this.fetchIsFleetUserStatus();
				// this.getUserWalletInfo();
				this.getFleetInfo();
			} else {
				this.resetState();
			}
		},
		onLoad() {
			// 监听消息全部已读事件
			uni.$on('messageReadEvent', () => this.menuList[5].value = 0)
		},
		methods: {
			...mapActions(['userLoginAction', 'userLogoutAction']),
			
			// 重置状态
			resetState() {
				this.vehicleItem = null;
				this.wallet = {
					balance: 0,
					freezePrice: 0,
					freezePriceChedui: 0,
					fleetBalance: 0
				};
				this.memberinfo = null;
				this.isVip = false;
				this.menuList[5].value = 0;
			},
			
			login() {
				this.$refs.login.openLogin()
			},
			//获取当前用户信息
			getmemberinfo(){
				this.$http_api.userInfo({}).then((res)=>{
					this.memberinfo = res;
					this.isVip = res.vip == 1;
					this.$store.dispatch('userLoginAction', res)
					uni.setStorageSync('userInfo', JSON.stringify(this.memberinfo))
					this.getUserWalletInfo();
					this.getVehicleList();
					this.getServicePhone();
					this.getMessageUnreadCount();
					this.getFleetInfo();
				})
			},
			// 新增一个方法来获取并设置 isFleetUser 状态
			async fetchIsFleetUserStatus() {
			    try {
			        const status = await getIsFleetUser(); // 调用缓存管理器中的函数
			        this.isFleetUser = status; // 将结果存入 data
			    } catch (error) {
			         // 处理错误，例如网络问题或 API 错误
			         console.error('获取 isFleetUser 状态失败:', error);
			         // 可以选择性地设置一个默认值，或者显示错误提示
			         // 为了安全起见，如果获取失败，可以默认隐藏（即设为 true），或者显示（设为 false）
			         // 这里我们假设获取失败时默认显示冻结金额（更保守）
			         this.isFleetUser = false;
			         // 或者显示用户友好的提示
			         // uni.showToast({ title: '获取用户状态失败', icon: 'none' });
			    }
			},
			// 获取用户钱包信息
			getUserWalletInfo() {
				this.$http_api.userWallet({}).then((res)=>{
					this.wallet = res
					this.setIdCardInfo();
				})
			},
			// 获取服务电话
			getServicePhone() {
				if (this.serviceHotLine) {
					return;
				}
				this.$http_api.serviceHotline().then(res => {
					this.serviceHotLine = res;
					this.menuList[4].value = res;
				})
			},
			// 获取未读消息
			getMessageUnreadCount() {
				this.$http_api.messageUnreadCount().then(res => {
					this.menuList[5].value = res;
				})
			},
			// 获取车辆列表
			getVehicleList() {
				this.$http_api.userVehicleList({}).then((res) => {
					if (res && res.length > 0) {
						const defaultCar = res.find(item => item.defaultSelected == 1)
						if (!defaultCar) return;
						let plateNumberArray = Array.from(defaultCar.plateNumber);
						plateNumberArray.splice(2, 0, '•');
						defaultCar.plateNumber = plateNumberArray;
						this.vehicleItem = defaultCar
					}
				})
			},
			gowallet() {
				uni.switchTab({ url: '/pages/wallet/wallet' });
			},
			//子组件给父组件传值
			uinfo(e) {
				this.getmemberinfo()
				this.username = e.username
				this.money = e.money
				if (e.id != '') {
					this.showlogin1 = false
					this.showlogin2 = true
				}
			},
			getIconPath(icon) {
				return `/static/mine/${icon}.png`
			},
			handleMenuClick(index) {
				const item = this.menuList[index];
				switch(item.icon) {
					case 'charging':
						uni.navigateTo({
							url: '/pages/user/users/charging/index'
						});
						break;
					case 'coupon':
						uni.navigateTo({
							url: '/pages/user/users/coupon/index'
						});
						break;
					case 'setting':
						uni.navigateTo({
							url: '/pages/user/users/setting/index'
						});
						break;
					case 'question':
						uni.navigateTo({
							url: '/pages/user/users/qa/index'
						});
						break;
					case 'notification':
						uni.navigateTo({
							url: '/pages/user/users/message/index'
						});
						break;
					case 'invoice':
						uni.navigateTo({
							url: '/pages/user/users/invoice/index'
						});
						break;
					case 'service':
						uni.makePhoneCall({ phoneNumber: this.serviceHotLine });
						break;
					case 'language':
						uni.navigateTo({
							url: '/pages/user/users/language/index'
						});
						break;
				}
			},
			
			topSelfHelp() {
				uni.navigateTo({
					url: '/pages/user/users/selfhelp/index'
				});
			},
			
			toLogin() {
				if (this.memberinfo) {
					uni.navigateTo({
						url: '/pages/user/users/info/index'
					});
					return
				}
				uni.navigateTo({ url: '/pages/public/login' })
			},
			
			toCarList() {
				uni.navigateTo({
					url: '/pages/user/users/car/index'
				});
			},

			goToWallet() {
				uni.navigateTo({
					url: '/pages/user/wallet/index'
				});
			},
			
			toVipPage() {
				uni.navigateTo({
					url: '/pages/user/users/vip/index'
				});
			},
			getFleetInfo() {
			        
			        this.$http_api.getFleetInfo().then(res => {
			            // 找到 menuList 中 icon 为 'fleet' 的项
			            const fleetItem = this.menuList.find(item => item.icon === 'fleet');
						if(res == null){
							fleetItem.value = '';
						}else if (fleetItem) {
			                // 将接口返回的名称赋值给 value 属性
			                fleetItem.value = res.fleetName; 
			            }
			        });
			},
			setIdCardInfo(){
				console.log("用户信息")
				console.log(this.memberinfo)
				console.log("钱包")
				console.log(this.wallet)
				const idCardItem = this.menuList.find(item => item.icon === 'idCard');
				if (this.memberinfo.idCard == null){
					idCardItem.value = '未绑定';
				}else{
					const idCardBalanceFen = this.wallet.idCardBalance || 0; // 避免 null/undefined 导致计算错误
					const idCardBalanceYuan = (idCardBalanceFen / 100).toFixed(2); // 格式化为两位小数
					idCardItem.value = `￥${idCardBalanceYuan}`; 
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		box-sizing: border-box;
		padding: 20rpx;

		.menu-list {
			background: #FFFFFF;
			border-radius: 24rpx;
			padding:  0;
			
			.menu-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 20rpx;
				position: relative;
				
				&:not(:last-child)::after {
					content: '';
					position: absolute;
					left: 90rpx; // 图标宽度 + 左边距
					right: 32rpx;
					bottom: 0;
					height: 1rpx;
					background: #EEEEEE;
				}
				
				.menu-left {
					display: flex;
					align-items: center;
					
					.menu-icon {
						width: 60rpx;
						height: 60rpx;
						border-radius: 16rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-right: 10rpx;
						
						.icon-image {
							width: 38rpx;
							height: 38rpx;
						}
					}
					
					.menu-title {
						font-size: 30rpx;
						color: #333;
						font-family: "PINGFANG";
						font-weight: 400;
					}
				}
				
				.menu-right {
					display: flex;
					align-items: center;
					
					.phone-number {
						font-size: 28rpx;
						color: #999;
						font-family: "PINGFANG";
						margin-right: 12rpx;
					}
					
					.fleet-name {
					    font-size: 28rpx;
					    color: #999; // 与服务热线相同的颜色
					    font-family: "PINGFANG";
					    margin-right: 30rpx; // 往左挪一点，增加右边距
					}
					
					.idCard-name {
					    font-size: 28rpx;
					    color: #999; // 与服务热线相同的颜色
					    font-family: "PINGFANG";
					    margin-right: 30rpx; // 往左挪一点，增加右边距
					}
					
					.service-phone {
						width: 58rpx;
						height: 58rpx;
					}
					
					.badge {
						background: #FF0000;
						color: #fff;
						font-size: 20rpx;
						width: 32rpx;
						height: 32rpx;
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-right: 12rpx;
					}
					
					.arrow-icon {
						width: 26rpx;
						height: 26rpx;
					}
				}
			}
		}
	}

	.hbg {
		padding: 0 3%;
		box-sizing: border-box;
		background-size: cover;
		padding-bottom: 30rpx;
		background: url('~@/static/mine/user-bg.png') no-repeat;
		background-size: 100% 85%;

		.head {
			padding-top: 60rpx;

			.pic {
				float: left;
			}

			.nickname {
				float: left;
				margin-top: 40rpx;
				margin-left: 10rpx;
				font-weight: bold;
				font-size: 30rpx;
				color: #444;
				border: 0;
				background: unset;
			}

			.nickname::after {
				border: 0;
			}

			.role {
				float: right;
				margin-top: 40rpx;
				background-color: #111734;
				padding: 10rpx 20rpx;
				border-radius: 40rpx;
			}
		}

		.user-info {
			display: flex;
			align-items: center;
			margin: 0 30rpx 40rpx 30rpx;
			
			.avatar {
				width: 120rpx;
				height: 120rpx;
				border-radius: 50%;
				border: 8rpx solid #8AC2F1;
				background: #fff;
			}
			
			.nickname {
				font-family: "PINGFANG";
				margin-left: 20rpx;
				font-size: 34rpx;
				color: #fff;
				font-weight: 600;
			}
			
			.phone {
				font-family: "PINGFANG";
				margin-left: 20rpx;
				font-size: 26rpx;
				color: #fff;
				font-weight: 400;
				margin-top: 10rpx;
			}
		}
		
		.vip-card {
			background: url('~@/static/mine/vip-bg.png') no-repeat;
			background-size: 100% 100%;
			border-radius: 49rpx 49rpx 0rpx 0rpx;
			padding: 20rpx 40rpx;
			margin: 0 20rpx;
			position: relative;
			
			.light-border {
				position: absolute;
				top: 0;
				left: -150%;
				width: 100%;
				height: 100%;
				background: linear-gradient(
					90deg,
					transparent,
					rgba(255, 255, 255, 0.2),
					transparent
				);
				// animation: light-move 3s infinite linear;
			}
			
			.triangle-bottom {
				position: absolute;
				bottom: -18rpx;
				left: 50%;
				transform: translateX(-50%);
				width: 0;
				height: 0;
				border-left: 30rpx solid transparent;
				border-right: 30rpx solid transparent;
				border-top: 20rpx solid #203FC7;
				border-bottom: none;
			}
			
			.vip-title {
				display: flex;
				align-items: center;
				
				.vip-icon {
					width: 54rpx;
					height: 54rpx;
					margin-right: 10rpx;
				}
				
				.vip-text {
					color: #F0D79F;
					font-size: 42rpx;
					font-weight: 400;
					font-family: "PINGFANG";
				}
				
				.vip-more {
					color: #F0D79F;
					font-size: 24rpx;
					font-weight: 400;
					font-family: "PINGFANG";
				}
			}
			
			// 非会员样式
			.title {
				align-self: flex-start;
				font-family: "PINGFANG";
				font-weight: 400;
				font-size: 42rpx;
				color: #F0D79F;
				text-shadow: 0px 1px 7px #00113F;
			}
			
			.desc {
				font-family: "PINGFANG";
				font-weight: 400;
				font-size: 24rpx;
				color: #A8AEE7;
			}
			
			.button {
				background: url('~@/static/mine/vip-button.png') no-repeat;
				background-size: 100% 100%;
				width: 180rpx;
				height: 70rpx;
				
				.text {
					font-family: "PINGFANG";
					font-weight: 500;
					font-size: 24rpx;
					color: #285095;
				}
			}
		}
		
		.wallet-info {
			background: #FFFFFF;
			border-radius: 24rpx;
			padding: 30rpx;
			
			.wallet-title {
				font-family: "PINGFANG";
				font-weight: 600;
				font-size: 35rpx;
				color: #333;
				margin-bottom: 20rpx;
				padding: 0 0 10rpx 0rpx;
				border-bottom: 1rpx solid #eee;
			}
			
			.wallet-amounts {
				display: flex;
				justify-content: space-between;
				
				.amount-item {
					text-align: center;
					// width: calc(100% / 3);
					position: relative;
					
					&:nth-child(2)::before {
						content: '';
						position: absolute;
						left: 0;
						top: 25%;
						width: 2rpx;
						height: 50%;
						background: #eee;
					}
					
					&:nth-child(2)::after {
						content: '';
						position: absolute;
						right: 0;
						top: 25%;
						width: 2rpx;
						height: 50%;
						background: #eee;
					}
					
					.amount {
						font-size: 38rpx;
						color: #FE6601;
						font-weight: 600;
						font-family: "PINGFANG";
					}
					
					.label {
						color: #333;
						margin-top: 10rpx;
						font-size: 28rpx;
						font-family: "PINGFANG";
						font-weight: 400;
					}
				}
			}
		}
	}
	
	.car {
		margin: 0 20rpx;
	}
			
	.car-header {
		display: flex;
		justify-content: space-between;
		background: linear-gradient( 145deg, #55D1F2 0%, #42E0A2 100%);
		border-radius: 21rpx 21rpx 0rpx 0rpx;
		margin: 0 20rpx;
		padding: 20rpx 40rpx;
		
		.title {
			color: #fff;
			font-family: "PINGFANG";
			font-weight: 600;
			font-size: 35rpx;
		}
		
		.view-all {
			color: #fff;
			font-size: 28rpx;
			font-family: "PINGFANG";
			font-weight: 400;
		}
	}
	
	.car-info {
		background: #FFFFFF;
		padding: 30rpx;
		margin-bottom: 20rpx;
		border-radius: 24rpx;
		
		.title {
			margin-bottom: 20rpx;
			.text {
				font-family: "PINGFANG";
				font-weight: 400;
				color: #333333;
				font-size: 29rpx;
			}
		}
		
		.plate-number {
			display: flex;
			justify-content: space-between;
			// gap: 20rpx;
			
			.plate-item {
				width: 60rpx;
				height: 60rpx;
				background: #F8F9FC;
				border-radius: 10rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 29rpx;
				color: #333;
				font-weight: 400;
				font-family: "PINGFANG";
			}
		}
		
		.no-car {
			flex-direction: column;
			padding: 20rpx 0;
			.text {
				font-family: "PINGFANG";
				font-weight: 400;
				font-size: 33rpx;
				color: #C0C8D5;
				margin-top: 20rpx;
			}
		}
	}
	
	.charge-btn {
		height: 85rpx;
		line-height: 85rpx;
		background: #42E0A2;
		border-radius: 43rpx;
		color: #FFFFFF;
		font-family: "PINGFANG";
		font-size: 28rpx;
		font-weight: 400;
		margin: 30rpx 40rpx 20rpx 40rpx;
		&::after {
			border: none;
		}
	}

	@keyframes light-move {
		0% {
			left: -150%;
		}
		100% {
			left: 150%;
		}
	}
</style>